import java.util.ArrayList;

/**
 * The Dealer distributes shares of the secret to
 * the servers in the host list.
 * @author jwallrab
 *
 */
public class Dealer {

	NetworkCommunicator net;
	ArrayList<String> servers;
	String filename = "hosts";
	String secretString = "";
	ShamirSecret secret;
	
	/**
	 * Constructor
	 * @param p The port to connect on
	 * @param s The Secret to be Split
	 * @param k The Number of Shares to Recover the Secret
	 */
	public Dealer(int p, String s, int k){
		
		net = new NetworkCommunicator(p);
		servers = FileIO.readFile(filename);
		secretString = s;
		secret = new ShamirSecret(secretString,k,servers.size());
		
		sendShares();
		
		secret.reconstruct();
	}
	
	/**
	 * Send the shares to the servers
	 */
	public void sendShares(){
		
		ArrayList<Share> shares = secret.getShares();
		
		for(int i = 0; i < servers.size(); ++i){
			try{
				net.sendConnect(servers.get(i));
				net.sendObject(shares.get(i));
				net.closeConnection();
				System.out.println("Sent " + shares.get(i).toString() + " to " + servers.get(i));
			}catch(Exception e){
				System.out.println("Error: Send failure to host " + servers.get(i));
			}
		}
	}
}
